import { createSlice } from '@reduxjs/toolkit'
import { PayloadAction } from '@reduxjs/toolkit'
import { AppDispatch } from '../../types/store'

const counterSlice = createSlice({
  name: 'counter',
  initialState: 66,
  reducers: {
    // 同步的action方法
    add (state, action: PayloadAction<number>) {
      console.log('---add----')
      return state + action.payload
    },
    minus (state, action: PayloadAction<number>) {
      console.log('---minus----')
      return state - action.payload
    }
  }
})

export const { add, minus } = counterSlice.actions

// 异步的action
export const asyncAdd = (payload: number): any => {
  return (dispatch: AppDispatch) => {
    setTimeout(() => {
      dispatch(add(payload))
    }, 1000)
  }
}

export default counterSlice.reducer
